package cn.edu.ljl;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

//用来添加文件信息、添加成功后、进入展示界面，使用file.html
//因为文件下载或在线浏览功能未成功完成，未加入到连接中，使用需要输入addFile

public class addFile extends HttpServlet {

    private static final int MEMORY_THRESHOLD = 1024*1024*3;
    private static final int MAX_FILE_SIZE = 1024*1024*40;
    private static final int MAX_REQUEST_SIZE = 1024*1024*50;

    private  static final String UPLOAD="uploadFile";


    private static final String INSERT_TEMPLATE =
            "INSERT INTO files (`nam`,`file`) " + "VALUES ('%s', '%s')";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String name   =  null;
        //检查是否是多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }

        //配置上传参数：
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置内存临界，超过将存放在临时目录
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        //设置临时存储目录
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload upload = new ServletFileUpload(factory);
        //设置文件上传最大值
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(MAX_REQUEST_SIZE);
        //中文处理
        upload.setHeaderEncoding("UTF-8");

        //构造临时路径来存储上传的文件
        //这个路径相对当前对应的目录
        String uploadPath = request.getServletContext().getRealPath("./")+File.separator+UPLOAD;
        File uploadDir = new File(uploadPath);
        if(!uploadDir.exists()){
            uploadDir.mkdir();
        }

        String file ="";
        try {
            //解析请求的内容提取数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems =upload.parseRequest(request);
            if(formItems !=null && formItems.size()>0){
                //迭代表单数据
                for (FileItem fileItem :formItems){
                    fileItem.getString("UTF-8");
                    if(!fileItem.isFormField()){
                        //处理不在表单中的数据
                        String fileName = new File(fileItem.getName()).getName();
                        String filePath = uploadPath+File.separator+fileName;
                        File storeFile = new File(filePath);
                        //控制台显示路径
                        System.out.println(filePath);
                        //保存到硬盘
                        fileItem.write(storeFile);
                        file += fileName ;
                    }else {
                        fileItem.getString("UTF-8");
                        request.setCharacterEncoding("UTF-8");
                        if(fileItem.getFieldName().equals("nam")){
                            name = fileItem.getString("UTF-8");
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }


        String sql  =  String.format(INSERT_TEMPLATE,name,file);
        System.out.println(sql);

        try {
            DBMS.insert(sql);
            response.sendRedirect("./file.html");
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }
}
